package com.lx.druid;


import com.alibaba.druid.pool.DruidDataSourceFactory;
import java.sql.Connection;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * Druid连接池的工具类
 */
public class Demo2 {
    //定义成员变量
    private static DataSource ds;

    static {
        try {
            //1. 加载配置文件
            Properties pro = new Properties();
            InputStream is = Demo2.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(is);
            //2. 获取DataSource连接池对象
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取连接
    public static Connection getConnection() throws SQLException {
        return  ds.getConnection();
    }

    /**
     *释放资源
     */
    public static void close(Statement stmt, Connection conn) throws SQLException {
        if (stmt!=null){
            stmt.close();
        }if (conn!=null){
            conn.close();
        }
    }
    /**
     * 获取连接池的方法
     */
    public static DataSource getDataSource(){
        return ds;
    }
}
